<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="用户名" v-model="username"></el-input>
      <el-input style="width: 200px; margin: 0 5px" placeholder="姓名" v-model="name"></el-input>
      <el-button type="primary" @click="userList(1)">查询</el-button>
      <el-button type="danger" @click="resetting">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      <el-button type="info" plain @click="exportData">批量导出</el-button>
      <el-upload action="http://localhost:8888/user/import"
                 :headers="{ token: user.token }"
                 :show-file-list="false"
                 :on-success="handleImport"
                 style="display: inline-block; margin-left: 10px"
      >
        <el-button type="primary" plain>批量导入</el-button>
      </el-upload>
    </div>
    <div style="display: flex">
      <div style="width: 150px;">
        <el-tree
            :props="props"
            :load="loadNode"
            lazy
            show-checkbox>
        </el-tree>
      </div>

      <el-table :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue' , color: '#666'}"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="序号" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="password" label="密码" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
        <el-table-column prop="address" label="地址" align="center"></el-table-column>
        <el-table-column label="头像" align="center">
          <template v-slot="scope">
            <el-image style="width: 50px; height: 50px; border-radius: 50%" v-if="scope.row.avatar"
                      :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :current-page="pageIndex"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="新增用户" :visible.sync="AddDialogFormVisible" width="40%">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px" style="margin-right: 20px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="邮箱邮箱"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" v-model="form.address" placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="form.role">
            <el-radio label="管理员"></el-radio>
            <el-radio label="用户"></el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="margin: 15px; text-align: center">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8888/file/upload"
              :headers="{ token: user.token} "
              :show-file-list="false"
              :on-success="handleAvatarSuccess">
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
<!--            <el-button type="primary">上传头像</el-button>-->
          </el-upload>
        </div>
        <div style="text-align: center; margin-bottom: 20px">
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "User",
  data() {
    return {
      props: {
        label: 'name',
        children: 'zones',
        isLeaf: 'leaf'
      },
      tableData: [], // 所有的数据
      pageIndex: 1, // 当前的页码
      pageSize: 5, // 每页显示的个数
      username: '', // 分页查询的用户名
      name: '', // 分页查询的姓名
      total: 0, // 数据的总条数
      AddDialogFormVisible: false,
      user: JSON.parse(localStorage.getItem('power-user') || '{}'), // 存储缓存
      form: {}, // 存储表单缓存
      rules: {
        username: [{required: true, message: '请输入用户名', trigger: 'blur'},],
        // name: [{required: true, message: '请输入姓名', trigger: 'blur'},],
        phone: [{required: true, message: '请输入电话', trigger: 'blur'},],
      },
      ids: []
    }
  },
  created() {
    this.userList()
  },
  methods: {
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ name: 'region' }]);
      }
      if (node.level > 1) return resolve([]);

      setTimeout(() => {
        const data = [{
          name: 'leaf',
          leaf: true
        }, {
          name: 'zone'
        }];

        resolve(data);
      }, 500);
    },

    // 批量导入数据
    handleImport(res,file,fileList){
      if (res.code === '200'){
        this.$message.success("导入成功")
        this.userList(1)
      }else {
        this.$message.error(res.msg)
      }
    },
    // 批量导出数据
    exportData(){
      // 没有选择行的时候全部导出，或者根据搜索条件导出
      if (!this.ids.length){
        window.open('http://localhost:8888/user/export?token='+ this.user.token
            + "&username=" + this.username + "&name="+ this.name)
      }else {      // [1,2,3] => '1,2,3'
        // 把数组转为字符串
        let idStr = this.ids.join(',')
        window.open('http://localhost:8888/user/export?token=' + this.user.token + '&ids=' + idStr)
      }
    },
    // 批量删除
    delBatch(){
      if (!this.ids.length){
        this.$message.warning("请选择要删除的数据")
        return
      }
      // 二次确认
      this.$confirm('您确认删除这些数据吗？','确认删除',{type: 'warning'}).then(res =>{
        this.$request.delete('/user/delete/batch',{data: this.ids}).then(res =>{
          if (res.code === '200'){
            this.$message.success("操作成功")
            this.userList(1)
          }else {
            this.$message.error(res.msg)
          }
        })
      }).catch(()=>{})
    },
    handleSelectionChange(rows){ // 当前选中行的所有数据
      console.log(rows)
      this.ids = rows.map(v => v.id)
      // console.log(ids)
    },
    // 单个删除
    del(id){
      // 二次确认
      this.$confirm('您确认删除吗？','确认删除',{type: 'warning'}).then(res =>{
        this.$request.delete('/user/delete/' + id).then(res =>{
          if (res.code === '200'){
            this.$message.success("操作成功")
            this.userList(1)
          }else {
            this.$message.error(res.msg)
          }
        })
      }).catch(()=>{})
    },
    handleAdd() { // 新增数据
      // 新增数据的时候清空数据
      this.form = {role: '用户'}
      // 打开弹窗
      this.AddDialogFormVisible = true
    },
    handleEdit(row){ // 编辑数据
      // 给form对象赋值，注意要深拷贝数据
      this.form = JSON.parse(JSON.stringify(row))
      // 打开弹窗
      this.AddDialogFormVisible = true
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把user的头像属性换成上传的图片的链接
      this.form.avatar = response.data
      //  根据数据刷新节点
      this.$forceUpdate() //组件嵌套太深 无法自动更新 强制更新视图
    },
    save() { // 保存按钮触发的逻辑 它会触发新增或者修改
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$request({
            // 因为修改是从行内元素拿到的，有id，因此可以作此判断
            // 判断有没id，如果有id说明是修改的方法，如果没有则是新增的方法
            method: this.form.id ? 'POST' : 'POST',
            url: this.form.id ? '/user/update' : '/user/add',
            data: this.form
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.userList(1)
              this.AddDialogFormVisible = false
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },

    resetting() {
      this.username = ''
      this.name = ''
      this.userList()
    },
    userList(pageIndex) { // 分页查询
      if (pageIndex) {
        this.pageIndex = pageIndex
      }
      request.get('/user/selectByPage', {
        params: {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          username: this.username,
          name: this.name,
        }
      }).then(res => {
        if (res.code == '200') {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    handleCurrentChange(pageIndex) {
      // 赋值
      this.pageIndex = pageIndex
      // 调用分页查询方法
      this.userList()
    }
  },
}
</script>

<style scoped>
/deep/ .avatar-uploader {
  border-radius: 50%;
}

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border-radius: 50%;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 50%;
}
</style>